function reactive (target) {
  return new Proxy(target, {
    get (target, key, receiver) {
      track(target, key) // 依赖追踪
      return Reflect.get(target, key)
    },

    set (target, key, value, receiver) {
      const flag = Reflect.set(target, key, value)
      trigger(target, key) // 触发
      return flag
    }
  })
}

const targetMap = new WeakMap()
let activeEffect

const effectStack = []

function cleanup (effectFn) {
  for (let i = 0; i < effectFn.deps.length; i++) {
    const deps = effectFn.deps[i]
    deps.delete(effectFn)
  }
  effectFn.deps.length = 0
}

function effect (fn, options = {}) {
  const effectFn = () => {
    cleanup(effectFn)
    activeEffect = effectFn
    effectStack.push(effectFn)
    fn()
    effectStack.pop()
    activeEffect = effectStack[effectStack.length - 1]
  }

  effectFn.deps = []
  effectFn.options = options
  effectFn()
}

function track (target, key) {
  if (!activeEffect) return

  let depsMap = targetMap.get(target)
  if (!depsMap) {
    targetMap.set(target, (depsMap = new Map()))
  }

  let deps = depsMap.get(key)
  if (!deps) {
    depsMap.set(key, (deps = new Set()))
  }

  deps.add(activeEffect)

  activeEffect.deps.push(deps) // 存储当前函数所有副作用set集合
}

function trigger (target, key) {
  const depsMap = targetMap.get(target)

  if (!depsMap) return

  const effects = depsMap.get(key)

  const effectsToRun = new Set()
  effects && effects.forEach(effectFn => {
    if (effectFn !== activeEffect) {
      effectsToRun.add(effectFn)
    }
  })
  effectsToRun.forEach(effectFn => {
    if (effectFn.options.scheduler) {
      effectFn.options.scheduler(effectFn)
    } else {
      effectFn()
    }
  })
}

const obj = reactive({
  a: 1,
  b: 2,
})

effect(function effect_1() {
  console.log(obj.a)
}, {
  scheduler (fn) {
    setTimeout(fn)
  }
})
obj.a = 2
console.log('结束了')
